import axios from "axios";
import store from "@/store/index.js";
import router from "@/router/router.js";
import { message } from "./singleMessage";
import { loading, startLoading, endLoading } from "./loading";
import errorCode from "@/const/errorCode.js";

window.axios = axios;
axios.defaults.timeout = 60000;
axios.defaults.baseURL = process.env.BASE_API;
// 记录请求接口的数量
let requestNum = 0;
// 记录完成请求的接口数量
let responseNum = 0;

// 请求前
axios.interceptors.request.use(
  config => {
    if (config.url.indexOf("portalLoading") > -1) {
      startLoading();
      console.log("startLoading");
    }
    const token = store.getters.access_token;
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    requestNum++;
    return config;
  },
  err => {
    requestNum++;
    Promise.reject(err);
  }
);

// 请求后
axios.interceptors.response.use(
  response => {
    let resCode = response.data.code;

    if (errorCode.includes(resCode)) {
      message.error(response.data.msg);
      // token过期
      if (resCode === 11001 || resCode === 11002) {
        store.dispatch("FedLogOut");
        router.push({ path: "/login" });
      }
    }

    responseNum++;
    if (loading && responseNum === requestNum) {
      endLoading();
    }
    return response;
  },
  error => {
    // 提示非后台返回的状态
    if (error.request.status !== 200) {
      message.error("服务器错误");
    }

    responseNum++;
    if (loading && responseNum === requestNum) {
      endLoading();
    }
    return Promise.reject(error.response.data);
  }
);

export default axios;
